import { on } from '@/libs/tools'
import { nextFocus } from '@/libs/ivuDom'

const directives = {
    /**
   * 回车focus 指令 v-focusJump="{onEnter, onLast, dynamic}"
   * value = {
   *  onEnter:Function  回车事件会调用的函数 返回 false 会阻止回车跳转
   *  onLast:Function  最后一个输入框回车会触发的事件
   *  dynamic:Boolean  表单输入框是否动态的 动态的会在回车事件时重新获取表单元素再进行跳转
   * }
   */
    focusJump: {
        bind (el, { value }) {
            let inputs = Array.from(el.querySelectorAll('input'))
            on(el, 'keyup', function (e) {
                if (e.keyCode == 13) {
                    if (value) {
                        const hanlderEnter = value.onEnter
                        if (hanlderEnter && hanlderEnter(e) === false) return
                        if (value.dynamic) {
                            inputs = Array.from(el.querySelectorAll('input'))
                        }
                        const next = nextFocus(e, inputs)
                        !next && value.onLast && value.onLast(e)
                    } else {
                        nextFocus(e, inputs)
                    }
                }
            })
        }
    }
}

export default {
    install (Vue) {
        Object.keys(directives).forEach(k => {
            Vue.directive(k, directives[k])
        })
    }
}
